import React, { Component } from "react";
import { Table, Input, Button, Popconfirm, Form ,Divider, Modal} from 'antd';
import Content from "../../components/Content/Content";

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} 不能为空.`,
              
            },
          ],
          initialValue: record[dataIndex],
        })(<Input className='InputValue' ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"

        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);

    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '新增分离菌株编号',
        dataIndex: 'add_separate_num',
      },
      {
        title: '退回时间',
        dataIndex: 'back_time',
      },
      {
        title: '退回原因',
        dataIndex: 'back_reason',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
      {
        title: '操作',
        dataIndex: 'operation',

        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="确认处理吗?" onConfirm={() => this.handleDelete(record)}>
             <Button type="dashed" disabled={ record.chuli_tag == 'yqr' } >
                是否处理
              </Button>
            </Popconfirm>
            
          ) : null,
      },
    ];
 
  }
  
  state = {
    dataSource: [],
    count: 0,
    loading: true,
    pageNum: 1,
    pageSize: 100
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.strainBack;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize})
    .then(res => {
     this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '加载数据出错!'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }
  onShowSizeChange = (current, pageSize) => {
    this.loadData(this.state.acqType, current, pageSize);
    this.setState({
        pageSize: pageSize
    })
  }

  paginationProps = {
    showSizeChanger: true,//设置每页显示数据条数
    showQuickJumper: false,
    showTotal: () => `共${this.state.count}条`,
    pageSize: this.state.pageSize,
    total: this.state.count,  //数据的总的条数
    onChange: (current) => this.loadData(current), //点击当前页码
    onShowSizeChange: (current, pageSize) => {//设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        console.log(pageSize);
        this.onShowSizeChange(current, pageSize)
    }
  }    

  handleDelete = record => {
    // 更新straininfo，设置chuli_tag为yqr

      record.chuli_tag = 'yqr';

      // 保存数据
      const url = global.api.strainInfo + record.id + '/';
      return global.updatedata.put(url, record)
      .then(res => {

        this.loadData(1);     

        Modal.success({
          content: '确认成功！'
        });

        this.cancel();
      })
      .catch(err => {
        Modal.error({
          content: 'Err: 确认失败！'
        })
      }) 

  };

  handleSave = row => {
    // 多余的代码，没有save操作
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
       <span style={{fontSize:'25px',marginLeft:"24px",fontFamily:'黑体'}}><b>操作进度</b></span>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={this.state.dataSource}
          pagination={this.paginationProps}
          columns={columns}
        />
      </Content>
    );
  }
}

const ActivityScreeningPrimary = Form.create()(EditableTable);
export default ActivityScreeningPrimary;
